package server;

import org.apache.http.HttpRequest;

import java.net.URLDecoder;
import java.util.HashMap;

/**
 * User: Jaan
 * Date: 10.12.11
 * Time: 14:36
 */
public class URIParser {
  HashMap<String, String> parameters;
  private static org.apache.log4j.Logger log = utils.Logger.getInstance(URIParser.class.getName());

  public URIParser(HttpRequest request) {
    parameters = new HashMap<String, String>();
    parseParameters(URLDecoder.decode(request.getRequestLine().getUri()));
  }

  private void parseParameters(String uri) {
    try {
      String[] params = uri.substring(uri.indexOf('?') + 1, uri.length()).split("[=&]");
      for (int i = 0; i < params.length; i = i + 2) {
        parameters.put(params[i], params[i + 1]);
      }
    } catch (Exception e) {
      log.info("Failed to get parameters from request: " + uri);
    }
  }

  public String getParameter(String parameterName) {
    return parameters.get(parameterName);
  }

}
